package com.example.demo.model.converter;

import com.example.demo.model.core.PageVo;
import com.example.demo.model.entity.SysLog;
import com.example.demo.model.form.LogForm;
import com.example.demo.model.form.UserForm;
import com.example.demo.model.vo.LogVO;
import com.example.demo.service.SysUserService;
import org.mapstruct.AfterMapping;
import org.mapstruct.Mapper;
import org.mapstruct.MappingTarget;
import org.springframework.beans.factory.annotation.Autowired;

@Mapper(componentModel = "spring")
public abstract class SysLogConverter {

    @Autowired
    protected SysUserService sysUserService;

    public abstract LogVO toVo(SysLog value);

    public abstract SysLog toEntity(LogForm value);

    public abstract LogForm toForm(SysLog value);

    public abstract PageVo<LogVO> toPageVo(PageVo<SysLog> pageVo);

    /**
     * 转换后处理：通过createBy查询用户名并设置到operator字段
     *
     * @param sysLog 源对象
     * @param logVO  目标对象
     */
    @AfterMapping
    protected void setOperator(@MappingTarget LogVO logVO, SysLog sysLog) {
        if (sysLog == null || sysLog.getCreateBy() == null) {
            return;
        }

        logVO.setOperator(getOperator(sysLog));
    }

    /**
     * 转换后处理：通过createBy查询用户名并设置到operator字段
     *
     * @param sysLog 源对象
     * @param logForm  目标对象
     */
    @AfterMapping
    protected void setOperator(@MappingTarget LogForm logForm, SysLog sysLog) {
        if (sysLog == null || sysLog.getCreateBy() == null) {
            return;
        }
        logForm.setOperator(getOperator(sysLog));

    }

    private String getOperator(SysLog sysLog) {
        String username = null;
        try {
            UserForm sysUser = sysUserService.form(sysLog.getCreateBy());
            if (sysUser != null && sysUser.getUsername() != null) {
                username = sysUser.getUsername();
            }
        } catch (Exception e) {
            // 查询失败时不影响主流程，operator保持为null
            // 可以记录日志，但这里不记录避免日志过多
        }
        return username;
    }
}
